package com.ctcemti.mdm.project.sys.service.impl;

import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultEnum;
import com.ctcemti.mdm.common.result.ResultUtil;
import com.ctcemti.mdm.common.util.JWTUtil;
import com.ctcemti.mdm.common.util.RedisUtil;
import com.ctcemti.mdm.common.util.StringUtils;
import com.ctcemti.mdm.project.sys.dao.CompanyMapper;
import com.ctcemti.mdm.project.sys.dao.RelPersonOrgMapper;
import com.ctcemti.mdm.project.sys.entity.OrgOrganization;
import com.ctcemti.mdm.project.sys.entity.RelPersonOrg;
import com.ctcemti.mdm.project.sys.entity.TreeObject;
import com.ctcemti.mdm.project.sys.service.ICommonService;
import com.ctcemti.mdm.project.sys.service.ICompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class CompanyServiceImpl implements ICompanyService {
    @Autowired
    CompanyMapper companyMapper;

    @Autowired
    RelPersonOrgMapper relPersonOrgMapper;

    @Autowired
    RedisUtil redisUtil;

    @Autowired
    private ICommonService commonService;

    @Override
    @Transactional
    public Result insertOrUpdate(OrgOrganization orgOrganization) {
        //orgOrganization.setParentId("9c22882f-3870-43fa-a563-785aa8091991");
        //是否名称重复
        if(!StringUtils.isNullOrEmpty(orgOrganization.getName().trim())){
            OrgOrganization temp = new OrgOrganization();
            temp.setName(orgOrganization.getName().trim());
            //判断父节点是否为空
            if(StringUtils.isNullOrEmpty(orgOrganization.getParentId())){
                temp.setParentId("");
            }else{
                temp.setParentId(orgOrganization.getParentId());
            }
            if(companyMapper.selectCount(temp)>1){
                return ResultUtil.error(ResultEnum.ZTSJ_1005);
            }
            //判断是否是修改时没有修改名字
            if(companyMapper.selectCount(temp)==1){
                OrgOrganization org = companyMapper.selectOne(temp);
                if(!org.getId().equals(orgOrganization.getId())){
                    return ResultUtil.error(ResultEnum.ZTSJ_1005);
                }
            }
        }else{
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }

        //简称是否重复
        if(!StringUtils.isNullOrEmpty(orgOrganization.getShortName())){
            OrgOrganization temp = new OrgOrganization();
            temp.setShortName(orgOrganization.getShortName().trim());
            temp.setParentId(orgOrganization.getParentId());
            if(companyMapper.selectCount(temp)>1){
                return ResultUtil.error(ResultEnum.ZTSJ_1005);
            }
            //判断是否是修改时没有修改
            if(companyMapper.selectCount(temp)==1){
                OrgOrganization org = companyMapper.selectOne(temp);
                if(!org.getId().equals(orgOrganization.getId())){
                    return ResultUtil.error(ResultEnum.ZTSJ_1005);
                }
            }
        }else{
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }
        //判断简码是否重复
        if(!StringUtils.isNullOrEmpty(orgOrganization.getOrgCode())){
            OrgOrganization temp = new OrgOrganization();
            temp.setOrgCode(orgOrganization.getOrgCode().trim());
            temp.setParentId(orgOrganization.getParentId());
            if(companyMapper.selectCount(temp)>1){
                return ResultUtil.error(ResultEnum.ZTSJ_1005);
            }
            //判断是否是修改时没有修改
            if(companyMapper.selectCount(temp)==1){
                OrgOrganization org = companyMapper.selectOne(temp);
                if(!org.getId().equals(orgOrganization.getId())){
                    return ResultUtil.error(ResultEnum.ZTSJ_1005);
                }
            }
        }

        //判断是需要新增还是修改
        if(orgOrganization.getId() == null){//新增
            //生成uuid
            orgOrganization.setId(UUID.randomUUID().toString());
            //保存
            companyMapper.insert(orgOrganization);
        }else{//修改
            companyMapper.updateByPrimaryKeySelective(orgOrganization);
        }
        return ResultUtil.success();
    }

    @Override
    public Result importOrgs(List<OrgOrganization> orgs) {
        if(orgs != null && orgs.size()>0){

        }
        return null;
    }

    @Override
    @Transactional
    public Result delete(OrgOrganization orgOrganization) {
        companyMapper.delete(orgOrganization);
        return ResultUtil.success();
    }

    @Override
    public Result<List<OrgOrganization>> getByPid(String pid) {
        List<OrgOrganization> orgs = new ArrayList<OrgOrganization>();
        OrgOrganization orgOrganization = new OrgOrganization();
        orgOrganization.setParentId(pid);
        //orgs = companyMapper.select(orgOrganization);该方法无法排序，因（singer）--bxf改
        Example example = new Example(OrgOrganization.class);
        example.setOrderByClause("sort asc");
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("parentId",pid);
        orgs = companyMapper.selectByExample(example);

        return ResultUtil.success(orgs);
    }

    @Override
    public Result<List<OrgOrganization>> getByPersonId(String personId) {
        List<OrgOrganization> result = new ArrayList<>();
        //根据personId获取对应的组织id
        RelPersonOrg relPersonOrg = new RelPersonOrg();
        relPersonOrg.setPersonId(personId);
        List<RelPersonOrg> relPersonOrgs = relPersonOrgMapper.select(relPersonOrg);
        //循环获取树的根节点
        if(relPersonOrgs!=null && relPersonOrgs.size()>0){
            for(RelPersonOrg temp:relPersonOrgs){
                OrgOrganization orgTemp = new OrgOrganization();
                orgTemp.setId(temp.getOrgId());
                //获取所在组织
                OrgOrganization pOrg = companyMapper.selectByPrimaryKey(orgTemp);
                //循环获取最上级父组织
                if(pOrg == null ){
                    return ResultUtil.success(result);
                }
                //获取上级组织判断是否类型是项目
                OrgOrganization pOrganization = new OrgOrganization();
                pOrganization.setId(pOrg.getParentId());
                pOrganization = companyMapper.selectByPrimaryKey(pOrganization);
                if(pOrganization.getType().equals(4)){
                    if(!result.contains(pOrganization)){
                        result.add(pOrganization);
                        continue;
                    }
                }
                //如果不是项目部则循环查出公司
                while(!pOrg.getType().equals(1)){
                    OrgOrganization oTemp = new OrgOrganization();
                    oTemp.setId(pOrg.getParentId());
                    pOrg = companyMapper.selectByPrimaryKey(oTemp);
                }
                //如果是中铁四局总公司
                if(pOrg.getParentId()==null || pOrg.getParentId().equals("")){
                    result.clear();
                    result.add(pOrg);
                    return ResultUtil.success(result);
                }
                if(!result.contains(pOrg)){
                    result.add(pOrg);
                }
            }
        }
        return ResultUtil.success(result);
    }

    @Override
    public List<OrgOrganization> selectChildById(String id) {
         return companyMapper.selectChildById(id);
    }

    /**
     * @Author bxf
     * @Description 获取根节点
     * @Date 11:29 2019/8/30
     * @param
     * @return java.util.List<com.ctcemti.mdm.project.sys.entity.OrgOrganization>
     */
    public List<OrgOrganization> selectRootById(){
        return companyMapper.selectRootById();
    }

    @Override
    public Result<List<OrgOrganization>> getByPersonIdForAdministrator(HttpServletRequest request) {
        List<OrgOrganization> orgs = new ArrayList<>();
        //根据personId获取对应的组织id
        //String loginId = JWTUtil.getLoginId(request.getHeader("Authorization"));
        //String loginName = JWTUtil.getLoginName(request.getHeader("Authorization"));
        Example example = new Example(OrgOrganization.class);
        example.setOrderByClause("sort asc");
        orgs = companyMapper.selectByExample(example);
        return new Result<List<OrgOrganization>>(ResultEnum.SUCCESS,orgs);

    }

    @Override
    public List<OrgOrganization> getOrgForTreeByName(HttpServletRequest request, String shortName, String loginId) {
        String personId = JWTUtil.getLoginId(request.getHeader("Authorization"));
        String loginName = JWTUtil.getLoginName(request.getHeader("Authorization"));
        List<TreeObject> result = new ArrayList<>();
        //从redis中根据人员id获取对应的所有组织
        List<OrgOrganization> orgOrganizationsForSelected = new ArrayList<>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);
        if(orgOrganizationsForSelected == null || orgOrganizationsForSelected.size() < 1){
            //插入关系
            if("Administrator".equals(loginName)){
                commonService.insertComRelationToRedisByPersonIdForAdministrator(personId);
            }else{
                commonService.insertComRelationToRedisByPersonId(personId);
            }
        }
        //commonService.insertComRelationToRedisByPersonId(personId);
        List<OrgOrganization> orglist_temp = new ArrayList<OrgOrganization>();
        orgOrganizationsForSelected = (List<OrgOrganization>) redisUtil.get(personId);

        List<String> temp = new ArrayList<String>();
        List<String> idtemp = new ArrayList<String>();//用于存放需要删除的项目id
        List<String> orgprojecttemp = new ArrayList<String>();
        for(OrgOrganization orgOrganization:orgOrganizationsForSelected){
            temp.add(orgOrganization.getId());
        }
        List<OrgOrganization> orgForTreeByName = companyMapper.getOrgForTreeByName(shortName);
        for(int i=0;i<orgForTreeByName.size();i++){
            if(!temp.contains(orgForTreeByName.get(i).getId())){
                orgForTreeByName.remove(i);
            }
        }
        return orgForTreeByName;
    }
}
